import { Injectable, Inject } from '@nestjs/common';
import { RedisService } from 'nestjs-redis';
import { Redis } from '../constants/redis.constant';
import { ConfigService } from '../../config/services/config.service';
import { ConfigProvider } from '../../config/constants/config.constant';

@Injectable()
export class RedisLantService {
  constructor(
    @Inject(ConfigProvider)
    private readonly configService: ConfigService,
    private readonly redisService: RedisService
  ) {}

  /** 获取Token数据库 */
  getTokenClient() {
    return this.redisService.getClient(this.configService.redis.token.name);
  }

  /**
   * 从Redis中取出数据
   * @param db Redis客户端
   * @param key 键
   */
  async get<T>(db: Redis, key: string): Promise<T> {
    const client = this.redisService.getClient(db);
    const data = await client.get(key);
    return new Promise(resolve => {
      try {
        const result = JSON.parse(data);
        resolve(result);
      } catch (error) {
        resolve((data as unknown) as T);
      }
    });
  }
}
